package com.limh.readers.fragment

import android.content.Intent
import android.os.Handler
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import butterknife.BindView
import com.limh.readers.R
import com.limh.readers.activity.WebInfoActivity
import com.limh.readers.bean.Article
import com.limh.readers.comm.Comm
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.LogUtil
import com.limh.readers.utils.Utils
import com.limh.readers.widget.recyclerview.adapter.CommonAdapter
import com.limh.readers.widget.recyclerview.adapter.MultiItemTypeAdapter
import com.limh.readers.widget.recyclerview.base.ViewHolder
import com.limh.readers.widget.recyclerview.decoration.SpacesItemDecoration
import com.squareup.picasso.Picasso
import rx.schedulers.Schedulers

/**
 * Function:随机文章列表
 * author: limh
 * time:2017/7/3
 */
class RandomFragment : BaseFragment() {
    @BindView(R.id.recy_radom)
    lateinit var recyRadom: RecyclerView
    @BindView(R.id.swipe_radom)
    lateinit var swipeRadom: SwipeRefreshLayout

    var articles: MutableList<Article>? = null
    var adapter: CommonAdapter<Article>? = null
    val TAG = "RandomFragment"

    override fun findViews(inflater: LayoutInflater?, container: ViewGroup?): View {
        return inflater?.inflate(R.layout.fragment_random, container, false) as View
    }

    override fun initViews() {
        articles = mutableListOf()
        val mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyRadom.layoutManager = mLayoutManager
        recyRadom.addItemDecoration(SpacesItemDecoration(Utils.dip2px(context, 4f), Utils.dip2px(context, 10f)))

        swipeRadom.setOnRefreshListener {
            articles!!.clear()
            getArticle()
        }
    }

    override fun initDatas() {
        getArticle()
    }

    private fun getArticle() {
        val params = mapOf(Pair("token", Comm.TOKEN), Pair("rand", "1"))
        val service = BaseRetrofit().createService(ServerApi::class.java)
        service.getArticle(params)
                .subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())
                .subscribe({ response ->
                    LogUtil.w(TAG, "response=" + response.toString())
                    when (response.getCode()) {
                        200 -> {
                            articles!!.addAll(GsonUtils.str2List(GsonUtils.Gson2Str(response.getData()), Article::class.java))
                            sendMsg("", 0x123, handler)
                        }
                        else -> {
                            sendMsg(response.getMessage(), 0x124, handler)
                        }
                    }
                }, {
                    sendMsg("网络异常", 0x124, handler)
                })
    }

    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0x123 -> {
                if (null == adapter) {
                    adapter = object : CommonAdapter<Article>(context, R.layout.view_item_art_list, articles!!) {
                        override fun convert(holder: ViewHolder, t: Article, position: Int) {
                            holder.setText(R.id.txt_item_art_title, t.artTitle!!)
                            holder.setText(R.id.txt_item_art_desc, t.artDesc!!)
                            holder.setText(R.id.txt_item_art_time, ( t.artClass + " " + t.artAuthor))
                            if (!TextUtils.isEmpty(t.artPic))
                                Picasso.with(context).load(t.artPic).into(holder.getView<View>
                                (R.id.image_item_art_pic) as ImageView)
                        }
                    }
                    adapter!!.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener {
                        override fun onItemClick(view: View, holder: RecyclerView.ViewHolder, position: Int) {
                            val intent = Intent(activity, WebInfoActivity::class.java)
                            intent.putExtra("id", articles!![position].id)
                            intent.putExtra("title", articles!![position].artTitle)
                            intent.putExtra("artLink", articles!![position].artUrl)
                            intent.putExtra("author", articles!![position].artAuthor)
                            intent.putExtra("table", "article")
                            startActivity(intent)
                        }
                    })
                    recyRadom.adapter = adapter
                } else {
                    adapter!!.datas = articles!!
                    adapter!!.notifyDataSetChanged()
                }
                for (item in articles!!)
                    LogUtil.w(TAG, "article=" + item.artTitle + " " + item.artPic)
            }
        }
        if (swipeRadom.isRefreshing) swipeRadom.isRefreshing = false
        true
    })
}